package com.nt.train.util.expands;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

/**
 * https://blog.csdn.net/buyaoshuohua1/article/details/107121350
 * @author hlf
 * @version 1.0
 * @date 2022/9/29 8:32
 */
@Component
public class SpringContextUtil implements BeanFactoryAware {

    private static BeanFactory beanFactory;

    /**
     * 实现BeanFactory接口的回调方法，设置上下文环境
     */
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory=beanFactory;
    }

    /**
     * 获取对象 这里重写了bean方法，起主要作用
     * @param beanId
     * @return  Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     */
    public static <T> T getBean(String beanId) throws BeansException {
        return (T)beanFactory.getBean(beanId);
    }

    /**
     * 获取对象 这里重写了bean方法，起主要作用
     * @param beanId
     * @return  Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     */
    public static <T> T getBean(String beanId,Class<T> beanClass) throws BeansException {
        return (T)beanFactory.getBean(beanId,beanClass);
    }
}
